package com.kmfish.smsbackup;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class SmsUtil {

	public static final String TAG = "SmsUtil";
	public static final Uri SMS_CONTENT_URI = Uri.parse("content://sms");
	public static final Uri SMS_INBOX_CONTENT_URI = Uri.withAppendedPath(
			SMS_CONTENT_URI, "inbox");
	public static final Uri SMS_SENT_CONTENT_URI = Uri.withAppendedPath(
			SMS_CONTENT_URI, "sent");
	
	public static final Uri MMSSMS_CANONICAL_ADDRESSES_URI = Uri.parse("content://mms-sms/canonical-addresses");
	public static final Uri MMSSMS_FULL_CONVERSATION_URI = Uri.parse("content://mms-sms/conversations");
	public static final Uri CONVERSATION_URI = MMSSMS_FULL_CONVERSATION_URI.buildUpon().appendQueryParameter("simple", "true").build();
	
	private static String getContactAddressById(Context context, String recipientIds)
	{
		String WHERE_CONDITION =  "_id" + " = '" + recipientIds + "'"; 
		Cursor cursor = context.getContentResolver().query(
				MMSSMS_CANONICAL_ADDRESSES_URI,
				null, WHERE_CONDITION, null, null);
		if (cursor != null) {
			try {
				cursor.moveToFirst();
				String recipIDs = cursor.getString(1);
				return recipIDs;
				
			} catch (Exception e) {
			}
		}
		return "";
	}
	
	public static MySmsMessage[] getSmsMessagesByThreadID(Context context, long threadID)
	{
		String WHERE_CONDITION =  "thread_id" + " = '" + threadID + "'"; 
		String SORT_ORDER = "date ASC";
		int count = 0;
		Cursor cursor = context.getContentResolver().query(
				SMS_CONTENT_URI,
				new String[] { "_id", "thread_id", "address", "person", "date",
						"type", "body" }, WHERE_CONDITION, null, SORT_ORDER);
		
		if (cursor != null) {
			try {
				count = cursor.getCount();
				MySmsMessage[] smsMessages = new MySmsMessage[count];
				if (count > 0) {
					int index = 0;
					while (cursor.moveToNext()) {
						
						String[] columns = cursor.getColumnNames();
						for (int i = 0; i < columns.length; i++) {
							Log.v(TAG, "columns " + i + ": " + columns[i] + ": "
									+ cursor.getString(i));
						}
						
						long messageId = cursor.getLong(0);
						long threadId = cursor.getLong(1);
						String address = cursor.getString(2);
						long contactId = cursor.getLong(3);
						String contactId_string = String.valueOf(contactId);
						long timestamp = cursor.getLong(4);
						int type = cursor.getInt(5);
						String body = cursor.getString(6);
						
						smsMessages[index++] = new MySmsMessage(context,
								address, contactId_string, body, timestamp,
								threadId, 0, messageId,
								type);
						
					}
					return smsMessages;
				}
			} finally {
				cursor.close();
			}
		}
		return null;
	}
	
	public static MySmsMessage[] getSmsMessagesByThread(Context context)
	{
		String SORT_ORDER = "date DESC";
		int threadCount = 0;
		Cursor cursor = context.getContentResolver().query(
				CONVERSATION_URI,
				new String[] { "_id", "date", "message_count", "recipient_ids",
						"snippet", "snippet_cs"}, null, null, SORT_ORDER);
		
		if (cursor != null) {
			try {
				threadCount = cursor.getCount();
				MySmsMessage[] smsMessages = new MySmsMessage[threadCount];
				if (threadCount > 0) {
					int index = 0;
					while (cursor.moveToNext()) {
						String[] columns = cursor.getColumnNames();
						for (int i = 0; i < columns.length; i++) {
							Log.v(TAG, "columns " + i + ": " + columns[i] + ": "
									+ cursor.getString(i));
						}
						
						long id = cursor.getLong(0);
						long date = cursor.getLong(1);
						long msgCount = cursor.getLong(2);
						String recipIDs = cursor.getString(3);
						String snippet = cursor.getString(4);
						String contactAddreass = getContactAddressById(context, recipIDs);
						smsMessages[index++] = new MySmsMessage(context,
								contactAddreass, recipIDs, snippet, date,
								id, msgCount, 0,
								0);
					}
					return smsMessages;
				}
			} finally {
				cursor.close();
			}
		}
		return null;
	}
	
	/**
	 * get sms messages on inbox or sentbox.
	 * @param isInbox
	 * @return
	 */
	public static MySmsMessage[] getSmsMessages(Context context, boolean isInbox)
	{
		Uri contentUri = isInbox ? SMS_INBOX_CONTENT_URI : SMS_SENT_CONTENT_URI; 
		String SORT_ORDER = "date DESC";
		int count = 0;
		
		Cursor cursor = context.getContentResolver().query(
				contentUri,
				new String[] { "_id", "thread_id", "address", "person", "date",
						"type", "body" }, null, null, SORT_ORDER);

		if (cursor != null) {
			try {
				count = cursor.getCount();
				MySmsMessage[] smsMessages = new MySmsMessage[count];
				if (count > 0) {
					int index = 0;
					while (cursor.moveToNext()) {
						
						String[] columns = cursor.getColumnNames();
						for (int i = 0; i < columns.length; i++) {
							Log.v(TAG, "columns " + i + ": " + columns[i] + ": "
									+ cursor.getString(i));
						}
						
						long messageId = cursor.getLong(0);
						long threadId = cursor.getLong(1);
						String address = cursor.getString(2);
						long contactId = cursor.getLong(3);
						String contactId_string = String.valueOf(contactId);
						long timestamp = cursor.getLong(4);
						int type = cursor.getInt(5);
						String body = cursor.getString(6);
						
						smsMessages[index++] = new MySmsMessage(context,
								address, contactId_string, body, timestamp,
								threadId, 0, messageId,
								type);
						
					}
					return smsMessages;
				}
			} finally {
				cursor.close();
			}
		}
		return null;
	}
	
	/*
     * 
     */
	public static MySmsMessage getSmsDetails(Context context,
			long ignoreThreadId, boolean unreadOnly) {

		String SMS_READ_COLUMN = "read";
		String WHERE_CONDITION = unreadOnly ? SMS_READ_COLUMN + " = 0" : null;
		String SORT_ORDER = "date DESC";
		int count = 0;

//		Log.v(TAG, WHERE_CONDITION);

		if (ignoreThreadId > 0) {
			Log.v(TAG, "Ignoring sms threadId = " + ignoreThreadId);
			WHERE_CONDITION += " AND thread_id != " + ignoreThreadId;
		}

		Cursor cursor = context.getContentResolver().query(
				SMS_CONTENT_URI,
				new String[] { "_id", "thread_id", "address", "person", "date",
						"type", "body" }, WHERE_CONDITION, null, SORT_ORDER);

		if (cursor != null) {
			try {
				count = cursor.getCount();
				if (count > 0) {
					cursor.moveToFirst();

					String[] columns = cursor.getColumnNames();
					for (int i = 0; i < columns.length; i++) {
						Log.v(TAG, "columns " + i + ": " + columns[i] + ": "
								+ cursor.getString(i));
					}

					long messageId = cursor.getLong(0);
					long threadId = cursor.getLong(1);
					String address = cursor.getString(2);
					long contactId = cursor.getLong(3);
					String contactId_string = String.valueOf(contactId);
					long timestamp = cursor.getLong(4);
					int type = cursor.getInt(5);
					String body = cursor.getString(6);
					
					if (!unreadOnly) {
						count = 0;
					}
					MySmsMessage smsMessage = new MySmsMessage(context,
							address, contactId_string, body, timestamp,
							threadId, count, messageId,
							type);

					return smsMessage;

				}
			} finally {
				cursor.close();
			}
		}
		return null;
	}

	public static MySmsMessage getSmsDetails(Context context) {
		return getSmsDetails(context, 0);
	}

	public static MySmsMessage getSmsDetails(Context context, boolean unreadOnly) {
		return getSmsDetails(context, 0, unreadOnly);
	}

	public static MySmsMessage getSmsDetails(Context context,
			long ignoreThreadId) {
		return getSmsDetails(context, ignoreThreadId, true);
	}

}
